package se.webbzon.boltzmann.game.object.action;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import se.webbzon.boltzmann.environment.AbstractEnvironment;
import se.webbzon.boltzmann.game.object.item.GameItemContainer;
import se.webbzon.oschi01.friendly.Friendly;
import se.webbzon.oschi01.worldobject.WorldObject;

public class ShopActionDeflation extends AbstractActionDeflation<GameItemContainer> {
	
	private String price;
	
	/*============================================================
	Constructors
	============================================================*/

	/** Creates a new empty sequence action deflation. **/
	public ShopActionDeflation(	int deflationProperties,
								WorldObject[] dependencies) {
		super(deflationProperties, dependencies);
	}
	
	/** Creates a new sequence action deflation from an existing
	 * sequence action. **/
	public ShopActionDeflation(	int deflationProperties,
								ShopAction shopAction) {
		super(deflationProperties, null, shopAction);
		price = shopAction.getPrice();
	}
	
	/*============================================================
	Public Methods
	============================================================*/

	@Override public void inflate(ByteBuffer buff) {
		super.inflate(buff);
		
		// Read from buffer
		byte[] priceData = new byte[buff.getShort()];
		buff.get(priceData, 0, priceData.length);
		try {
			price = new String(priceData,"utf-8");
		} catch (UnsupportedEncodingException e) {
			price = "";
		}
	}

	@Override public ByteBuffer deflate(int allocate) {
		byte[] priceData;
		try {
			priceData = price.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			priceData = new byte[0];
		}
		ByteBuffer buff = super.deflate(allocate + 6 + priceData.length);
		
		// Write to buffer
		buff.putShort((short) priceData.length);
		buff.put(priceData);
		
		return buff;
	}
	
	/*============================================================
	Friendly Methods
	============================================================*/
	
	@Friendly WorldObject makeSequenceAction(AbstractEnvironment env) {
		return new ShopAction(env,getParent(),price,getFrontOnly(),getRange());
	}
	
}
